# -*- encoding:utf-8 -*-
# @Time: 2022/11/9 18:51
# @Author :xibin
# @Email: xibin@maqu. com
# @File: serializer.py
# @Software: PyCharm
from rest_framework.fields import SerializerMethodField #自定义方法显示字段
from rest_framework.serializers import Serializer,ModelSerializer
from .models import *
from users.serializers import UserSerializer


class ClassesSerializers(ModelSerializer):
    memberDetails = SerializerMethodField() #使用自定义显示字段

    class Meta:
        model = Classes
        exclude = ['is_delete']

    def get_memberDetails(self, instance):
        #分类
        members = UserSerializer(instance.member.all(),many=True).data #获取当前班级所有的用户数据查询集,因为是查询集，所以要.data拿出数据并序列化操作
        return {
            'teachers':[i['username'] for i in members if i['is_superuser'] or 1 in i['groups']],
            #表示如果auth_user表里有 1组(老师组，id为1)或者有超级管理员，就从得到的members(数据)中提取出username(名字),放到这里
            'students':[i['username'] for i in members if 2 in i['groups']],
            #表示如果auth_user表里有第二组(学生组，id为2)，就从获取的members中提取username(名字)，放到此处
        }

class CreateUserSerializer(ModelSerializer):
    class Meta:
        model = User
        fields = ['username','first_name','email']  #显示的字段信息
        extra_kwargs = {
            'username': {'required':True}, #限制是唯一的，表示不可以重名
            'email': {'required':True}, #限制是唯一的，
        }





